
import { useState } from "react";
import { useHistory, useLocation } from "react-router";
import { Button, Drawer, Form, Input, message, Modal, Select, Space } from "antd";
// import ActionForm from "./ActionForm";
import { submitAction } from "./service";
import { useModel } from "umi";

interface IActionModal {
  title: string;
  visible: boolean;
  type: string;
  onSubmit: (data: any) => void;
  onCancel: () => void;
  loading: boolean;
  cancelName: string;
}

const ActionModal: React.FC<IActionModal> = (props) => {
  const [form] = Form.useForm();
  return (
    <Modal confirmLoading={props.loading} title={props.title} destroyOnClose visible={props.visible} onOk={async () => {
      const values = await form.validateFields();
      props.onSubmit(values);
      form.resetFields();
      props.onCancel();
    }} onCancel={() => {
      form.resetFields();
      props.onCancel();
    }}>
      <Form form={form} layout="vertical"
        initialValues={['reject'].includes(props.type) ? {
          startName: '提交人',
          situation: '按原流程步骤逐步运行',
          cancelName: props.cancelName
        } : {}}
      >
        {
          ['communicate', 'turn'].includes(props.type) && <Form.Item label="请选择人员" name="user" rules={[{ required: true, message: '请选择人员' }]} >
            <Select>
              <Select.Option value="9346">古福艳</Select.Option>
            </Select>
          </Form.Item>
        }
        {
          ['reject'].includes(props.type) && <>
            <Form.Item label="驳回到活动" name="startName">
              <Select>
                <Select.Option value="提交人">提交人</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item label="流转方式" name="situation">
              <Select>
                <Select.Option value="直接回到本活动">直接回到本活动</Select.Option>
                <Select.Option value="按原流程步骤逐步运行">按原流程步骤逐步运行</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item hidden name="cancelName">
              <Input />
            </Form.Item>
          </>
        }
      </Form>
    </Modal>
  )
}
interface Props {
  detailData: any;
  processList: any[]
}

const ProcessAction = (props: Props) => {
  const [visible, setVisible] = useState(false);
  const [form] = Form.useForm();
  const location = useLocation();
  const history = useHistory();
  const { taskId } = (location as any).query;
  const { initialState } = useModel('@@initialState');
  const [actionType, setActionType] = useState('');
  const [submitLoading, setSubmitLoading] = useState(false);
  const [visibleType, setVisibleType] = useState(false);
  const getCurrentNode = props.processList.find(item => item.flag === '1');
  const isRejected = !props.processList.find(item => ['1', '3'].includes(item.flag)); // 是否驳回单
  const approveUserIdList = getCurrentNode?.list && getCurrentNode?.list?.map((item: { userId: any; }) => item.userId);

  const _submitAction = async (data: any, type = actionType) => {
    await form.validateFields();
    setSubmitLoading(true);
    const detailData = props.detailData;
    const res = await submitAction({
      data: data || null,
      instanceId: detailData.instanceId || '',
      nodeName: getCurrentNode?.processNode || '提交人',
      operate: type,
      opinion: form.getFieldValue('description') || '',
      serialNum: detailData.serialNum,
      taskId,
      tmpUuid: detailData.tmpUuid
    });
    if (res.errorCode === '0') {
      setVisibleType(false);
      setVisible(false);
      message.success('请求成功！', 2, () => {
        history.push('/approval')
      });
    }
    setSubmitLoading(false);
  }
  const approveAction = async (type: string) => {
    await form.validateFields(['description']);
    if (type !== 'agree') {
      setVisibleType(true);
    } else {
      _submitAction(null, 'agree');
    }
    setActionType(type);
  }
  const returnActionBtn = () => {
    if (approveUserIdList?.includes(initialState?.userInfo.userId) || isRejected && props.processList[0]?.list[0]?.userId === initialState?.userInfo.userId) {
      return <Button type="primary"
        loading={actionType === 'agree' ? submitLoading : false}
        disabled={actionType !== 'agree' ? submitLoading : false}
        onClick={() => {
          approveAction('agree');
        }}>{isRejected ? '提交' : '同意'}</Button>
    }
    return ''
  }

  return (
    <div>
      <Button type='primary' onClick={() => setVisible(true)}>审批操作</Button>
      <Drawer
        title="审批意见"
        width={720}
        onClose={() => setVisible(false)}
        maskClosable={false}
        visible={visible}
        bodyStyle={{ paddingBottom: 80 }}
        footer={
          <Space style={{ float: 'right' }}>
            <Button disabled={submitLoading} onClick={() => setVisible(false)}>取消</Button>
            {approveUserIdList?.includes(initialState?.userInfo.userId) && <>
              <Button ghost
                loading={actionType === 'communicate' ? submitLoading : false}
                disabled={actionType !== 'communicate' ? submitLoading : false}
                type="primary" onClick={() => approveAction('communicate')}>沟通</Button>
              <Button ghost
                loading={actionType === 'turn' ? submitLoading : false}
                disabled={actionType !== 'turn' ? submitLoading : false}
                type="primary" onClick={() => approveAction('turn')}>转办</Button>
              <Button danger
                loading={actionType === 'reject' ? submitLoading : false}
                disabled={actionType !== 'reject' ? submitLoading : false}
                onClick={() => approveAction('reject')}>驳回</Button>

            </>}
            {
              returnActionBtn()
            }
          </Space>
        }
      >
        {/* 审批表单 */}
        {/* <ActionForm /> */}
        <Form form={form} layout="vertical" >
          <Form.Item
            name="description"
            label="审批原因"
            rules={[
              {
                required: true,
                message: '请输入审批原因',
              },
            ]}
          >
            <Input.TextArea rows={4} placeholder="请输入审批原因" />
          </Form.Item>
        </Form>
        <ActionModal
          title='ssssss'
          cancelName={getCurrentNode?.processNode || ''}
          visible={visibleType}
          type={actionType}
          loading={submitLoading}
          onSubmit={_submitAction}
          onCancel={() => {
            setVisibleType(false)
          }} />
      </Drawer >
    </div >
  )
}

export default ProcessAction;
